#include "socket.hpp"
#include "protocol.hpp"

void Usage(const std::string &proc)
{
    cout << "you can use " << proc << " port" << endl;
}

void *handler_request(void *args)
{
    pthread_detach(pthread_self());
    int sock = *(int *)args;
    delete (int *)args;

    // 业务逻辑

#define NUM 1024
    char s[NUM] = {0};
    ssize_t ret = read(sock, s, sizeof(s));
    cout << s << endl;

    if (ret > 0)
    {
        // 反序列化
        request_t rq;
        memset(&rq, 0, sizeof(rq));
        std::string str = s;
        deserialize_request(str, rq);
        cout << "rq : " << rq.x << " " << rq.op << " " << rq.y << endl;

        // 构建响应
        response_t resp = {0, 0};
        switch (rq.op)
        {
        case '+':
            resp.result = rq.x + rq.y;
            break;
        case '-':
            resp.result = rq.x - rq.y;
            break;
        case '*':
            resp.result = rq.x * rq.y;
            break;
        case '/':
            if (rq.y == 0)
                resp.code = -1; // 除零错误
            break;
        case '%':
            if (rq.x == 0)
                resp.code = -1; // 除零错误
            break;
        default:
            resp.code = -3;
            break;
        }
        // 序列化
        string echo_string = serialize_response(resp);
        cout << echo_string << endl;
        write(sock, echo_string.c_str(), echo_string.length());
    }
}
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(1);
    }
    int listen_sock = Sock::Socket();
    Sock::Bind(listen_sock, atoi(argv[1]));
    Sock::Listen(listen_sock);

    for (;;)
    {
        int new_sock = Sock::Accept(listen_sock);

        pthread_t tid;
        int *parm = new int(new_sock);
        pthread_create(&tid, nullptr, handler_request, (void *)parm);
    }

    return 0;
}